import React, { useState } from 'react';
import { TaskPlan, DetectedTask } from '../../types';
import { GlassCard, GlassButton } from '../ui';

interface TaskPlanDisplayProps {
  /** 检测到的任务列表 */
  tasks: DetectedTask[];
  /** 生成的计划列表 */
  plans: TaskPlan[];
  /** 是否正在加载 */
  isLoading?: boolean;
  /** 复制回调 */
  onCopy?: (text: string) => void;
}

/**
 * 任务计划展示组件
 * 展示检测到的任务和生成的计划
 * Requirements: 4.5
 */
export const TaskPlanDisplay: React.FC<TaskPlanDisplayProps> = ({
  tasks,
  plans,
  isLoading = false,
  onCopy,
}) => {
  const [copiedPlanId, setCopiedPlanId] = useState<string | null>(null);
  const [expandedPlanId, setExpandedPlanId] = useState<string | null>(null);

  const handleCopyPlan = async (plan: TaskPlan) => {
    try {
      await navigator.clipboard.writeText(plan.shareableText);
      setCopiedPlanId(plan.taskId);
      onCopy?.(plan.shareableText);
      setTimeout(() => setCopiedPlanId(null), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const toggleExpand = (planId: string) => {
    setExpandedPlanId(prev => prev === planId ? null : planId);
  };

  const getPriorityColor = (priority: string) => {
    const colorMap: Record<string, string> = {
      high: 'bg-red-100 text-red-600',
      medium: 'bg-yellow-100 text-yellow-700',
      low: 'bg-green-100 text-green-600',
    };
    return colorMap[priority] || 'bg-gray-100 text-gray-600';
  };

  const getPriorityLabel = (priority: string) => {
    const labelMap: Record<string, string> = {
      high: '高',
      medium: '中',
      low: '低',
    };
    return labelMap[priority] || priority;
  };

  const formatDate = (date: Date | undefined) => {
    if (!date) return null;
    return new Date(date).toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  if (isLoading) {
    return (
      <GlassCard className="animate-pulse-soft overflow-hidden">
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <div className="h-5 w-16 bg-emerald-100 rounded animate-shimmer"></div>
            <div className="h-5 w-24 bg-emerald-100 rounded animate-shimmer" style={{ animationDelay: '0.1s' }}></div>
          </div>
          <div className="h-5 bg-emerald-100 rounded w-3/4 animate-shimmer" style={{ animationDelay: '0.15s' }}></div>
          <div className="h-4 bg-emerald-50 rounded w-1/2 animate-shimmer" style={{ animationDelay: '0.2s' }}></div>
          <div className="border-t border-emerald-100 pt-3 mt-3">
            <div className="space-y-2">
              <div className="h-4 bg-emerald-50 rounded w-full animate-shimmer" style={{ animationDelay: '0.25s' }}></div>
              <div className="h-4 bg-emerald-50 rounded w-5/6 animate-shimmer" style={{ animationDelay: '0.3s' }}></div>
              <div className="h-4 bg-emerald-50 rounded w-2/3 animate-shimmer" style={{ animationDelay: '0.35s' }}></div>
            </div>
          </div>
        </div>
      </GlassCard>
    );
  }

  if (tasks.length === 0) {
    return (
      <GlassCard className="text-center py-6">
        <p className="text-2xl mb-2">📋</p>
        <p className="text-gray-500 text-sm">未检测到任务</p>
        <p className="text-gray-400 text-xs mt-1">聊天中包含任务时会自动识别</p>
      </GlassCard>
    );
  }

  return (
    <div className="space-y-4">
      <h3 className="text-emerald-700 text-sm font-medium">
        检测到的任务 ({tasks.length})
      </h3>
      
      {tasks.map((task, taskIndex) => {
        const plan = plans.find(p => p.taskId === task.id);
        const isExpanded = expandedPlanId === task.id;
        
        return (
          <GlassCard 
            key={task.id}
            className="animate-slide-up"
            style={{ animationDelay: `${taskIndex * 0.1}s` } as React.CSSProperties}
          >
            {/* 任务头部 */}
            <div className="flex items-start justify-between gap-3 mb-3">
              <div className="flex-1">
                <div className="flex items-center gap-2 mb-1">
                  <span className={`px-2 py-0.5 rounded text-xs ${getPriorityColor(task.priority)}`}>
                    {getPriorityLabel(task.priority)}优先级
                  </span>
                  {task.deadline && (
                    <span className="px-2 py-0.5 bg-orange-100 rounded text-xs text-orange-600">
                      📅 {formatDate(task.deadline)}
                    </span>
                  )}
                </div>
                <p className="text-gray-700 font-medium">{task.description}</p>
                {task.participants.length > 0 && (
                  <p className="text-gray-500 text-sm mt-1">
                    👥 参与者: {task.participants.join(', ')}
                  </p>
                )}
              </div>
            </div>
            
            {/* 计划详情 */}
            {plan && (
              <div className="border-t border-emerald-200 pt-3 mt-3">
                <div 
                  className="flex items-center justify-between cursor-pointer"
                  onClick={() => toggleExpand(task.id)}
                >
                  <h4 className="text-emerald-600 text-sm font-medium">
                    📝 {plan.title}
                  </h4>
                  <span className="text-gray-400 text-sm">
                    {isExpanded ? '收起' : `${plan.steps.length} 个步骤`}
                  </span>
                </div>
                
                {isExpanded && (
                  <div className="mt-3 space-y-2 animate-fade-in">
                    {plan.steps.map((step) => (
                      <div 
                        key={step.order}
                        className="flex items-start gap-2 pl-2 border-l-2 border-emerald-300"
                      >
                        <span className="text-gray-400 text-sm min-w-[20px]">
                          {step.order}.
                        </span>
                        <div className="flex-1">
                          <p className="text-gray-700 text-sm">{step.description}</p>
                          <div className="flex gap-2 mt-1 flex-wrap">
                            {step.assignee && (
                              <span className="text-gray-500 text-xs">
                                👤 {step.assignee}
                              </span>
                            )}
                            {step.estimatedTime && (
                              <span className="text-gray-500 text-xs">
                                ⏱️ {step.estimatedTime}
                              </span>
                            )}
                            {step.deadline && (
                              <span className="text-gray-500 text-xs">
                                📅 {formatDate(step.deadline)}
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                    
                    {/* 摘要 */}
                    <div className="mt-3 p-2 bg-emerald-50 rounded-lg">
                      <p className="text-gray-600 text-sm">{plan.summary}</p>
                    </div>
                  </div>
                )}
                
                {/* 复制按钮 */}
                <div className="mt-3 flex justify-end">
                  <GlassButton
                    size="sm"
                    onClick={() => handleCopyPlan(plan)}
                  >
                    {copiedPlanId === plan.taskId ? (
                      <span className="text-emerald-600">✓ 已复制</span>
                    ) : (
                      <span>📋 复制计划</span>
                    )}
                  </GlassButton>
                </div>
              </div>
            )}
          </GlassCard>
        );
      })}
    </div>
  );
};

export default TaskPlanDisplay;
